// 将live页面逻辑相关的所有网络请求代码，统一放在这个文件里面管理
import request from "../request";
import axios from "axios";

export const startGet = async () => {
  let res = await request.get("/classes/Star");
  console.log("api板块发起请求", res);
  return res.data.results; //必须return数据后，调用startGet的页面才能拿到数据
};

//爬取并转存生活馆数据
export const liveSave = async () => {
  //1. 获取第三方数据
  let url = "/heheda/proxy/articles/featured/list?limit=1000&offset=0";
  let res = await axios.get(url); //请求第三方接口，必须要使用未封装的原始axios
  console.log("通过本地代理获取数据", res);
  let arr = res.data.results; //
  let saveData = [];
  // 2. 将第三方数据处理为批量操作接口所要求的格式
  for (let i = 0; i < arr.length; i++) {
    saveData.push({
      method: "POST", // 1. 这一条数据执行什么操作
      path: "/1.1/classes/live", //2. 批量操作目标表
      body: arr[i],
    });
  }
  // 3. 将数据批量提交只LeanCloud
  let res1 = await request.post("/batch", { requests: saveData });
};

// 加载生活馆列表
// page 是当前页码
// pageSize 是每页下发的条数
// styleName 是用户搜索框输入的条件
export const liveGet = async (page = 1, pageSize = 12, styleName) => {
  let skip = (page - 1) * pageSize; //根据页码计算需要跳过的数据条数
  let condition = styleName ? `&where={"style_name":"${styleName}"}` : ""; //用户不传递搜索条件，则不带where
  let res = await request.get(
    `/classes/live?count=1&limit=${pageSize}&skip=${skip}${condition}`
  );
  console.log("查询结果", res);
  return res.data; //{count:xxx,results:[]}
};

export const petGet = async () => {
  let url = `/epet/v3/goods/category/main.html?do=getChildren&owner=5&pet_type=dog&issite=true&version=358&system=wap&isWeb=1&distinct_id=1909ba956fb3f7-012e443c67007b-590c373d-329160-1909ba956fc8ea&_=1720598521660`;
  let res = await axios.get(url);
};

// 删除生活馆数据
export const liveDel = async (objectId) => {
  //数据唯一id
  try {
    let res = await request.delete(`/classes/live/${objectId}`); // 模板字符串，注意引号比较特殊
    console.log("删除成功", res);
    return {
      message: "删除成功",
      type: "success",
    };
  } catch (error) {
    console.log("删除失败", error);
    return {
      message: "删除失败",
      type: "error",
    };
  }
};

// 更新数据
export const livePut = async (objectId, newLiveData) => {
  //数据唯一id
  try {
    let res = await request.put(`/classes/live/${objectId}`, newLiveData); // 模板字符串，注意引号比较特殊
    console.log("更新成功", res);
    return {
      message: "更新成功",
      type: "success",
    };
  } catch (error) {
    console.log("更新失败", error);
    return {
      message: "更新失败",
      type: "error",
    };
  }
};
